using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace WPFTemplateLib.Controls
{
	/// <summary>
	/// [控件] 增强版 TextBlock
	/// </summary>
	public class TextBlockEx : TextBlock
	{
		/// <inheritdoc />
		protected override Geometry GetLayoutClip(Size layoutSlotSize)
		{
			IsTextTrimmed = GetIsTrimming();
			IsTextBeCutOff = GetIsTextBeCutOff();

			return base.GetLayoutClip(layoutSlotSize);
		}

		#region 判断当前文字是否被截断

		//https://blog.csdn.net/u012046379/article/details/119517156

		/// <summary>
		/// 文本是否未完全显示
		/// </summary>
		public bool IsTextTrimmed
		{
			get { return (bool)GetValue(IsTextTrimmedProperty); }
			private set { SetValue(IsTextTrimmedProperty, value); }
		}
		public static readonly DependencyProperty IsTextTrimmedProperty =
			DependencyProperty.Register(nameof(IsTextTrimmed), typeof(bool), typeof(TextBlock), new PropertyMetadata(false));

		private bool GetIsTrimming()
		{
			if(TextTrimming == TextTrimming.None)
			{
				return false;
			}

			if(TextWrapping == TextWrapping.NoWrap)  //比较长度
			{
				Size size = new Size(double.MaxValue, RenderSize.Height);
				var needsize = MeasureOverride(size);

				if(needsize.Width > RenderSize.Width)
				{
					MeasureOverride(RenderSize);
					return true;
				}
			}
			else  //比较高度
			{
				Size size = new Size(RenderSize.Width, double.MaxValue);
				var needsize = MeasureOverride(size);
				if(needsize.Height > RenderSize.Height)
				{
					MeasureOverride(RenderSize);
					return true;
				}
			}

			return false;
		}

		/// <summary>
		/// 文本是否被截断
		/// </summary>
		public bool IsTextBeCutOff
		{
			get { return (bool)GetValue(IsTextBeCutOffProperty); }
			private set { SetValue(IsTextBeCutOffProperty, value); }
		}
		public static readonly DependencyProperty IsTextBeCutOffProperty =
			DependencyProperty.Register(nameof(IsTextBeCutOff), typeof(bool), typeof(TextBlock), new PropertyMetadata(false));

		private bool GetIsTextBeCutOff() => GetIsTextBeCutOff(this);

		/// <summary>
		/// [DeepSeek] 获取文本是否超出显示范围(被截断)
		/// </summary>
		/// <param name="textBlock">TextBlock 对象</param>
		/// <returns>文本是否被截断</returns>
		private bool GetIsTextBeCutOff(TextBlock textBlock)
		{
			// 计算文本的实际宽度
			var formattedText = new FormattedText(
				textBlock.Text,
				CultureInfo.CurrentCulture,
				FlowDirection.LeftToRight,
				new Typeface(textBlock.FontFamily, textBlock.FontStyle, textBlock.FontWeight, textBlock.FontStretch),
				textBlock.FontSize,
				Brushes.Black,
				new NumberSubstitution(),
				VisualTreeHelper.GetDpi(textBlock).PixelsPerDip);

			// 获取 TextBlock 的 Padding
			var padding = textBlock.Padding;

			// 计算实际可用的文本显示宽度
			double availableWidth = textBlock.ActualWidth - padding.Left - padding.Right;

			// 比较文本宽度和实际可用宽度
			return formattedText.Width > availableWidth;
		}

		#endregion
	}
}
